import { TransformConfig } from '../types';

export class ConfigTransformer {
  private config: TransformConfig;

  constructor(config: TransformConfig) {
    this.config = config;
  }

  async transformJSON(content: string, filePath: string): Promise<string> {
    try {
      const jsonData = JSON.parse(content);
      
      // 根据文件类型进行不同的转换
      if (filePath.includes('app.json')) {
        return this.transformAppConfig(jsonData);
      } else if (filePath.includes('project.config.json')) {
        return this.transformProjectConfig(jsonData);
      } else {
        // 其他JSON文件保持原样
        return content;
      }
    } catch (error) {
      console.warn(`Failed to parse JSON file ${filePath}:`, error);
      return content;
    }
  }

  private transformAppConfig(appConfig: any): string {
    // 转换app.json为Taro配置
    const taroConfig = {
      pages: appConfig.pages || [],
      window: appConfig.window || {},
      tabBar: appConfig.tabBar || {},
      networkTimeout: appConfig.networkTimeout || {},
      debug: appConfig.debug || false,
      subPackages: appConfig.subpackages || [],
      preloadRule: appConfig.preloadRule || {},
      workers: appConfig.workers || '',
      requiredBackgroundModes: appConfig.requiredBackgroundModes || [],
      plugins: appConfig.plugins || {},
      resizable: appConfig.resizable || false,
      usingComponents: appConfig.usingComponents || {},
      permission: appConfig.permission || {},
      sitemapLocation: appConfig.sitemapLocation || 'sitemap.json',
      style: appConfig.style || 'v2',
      lazyCodeLoading: appConfig.lazyCodeLoading || 'requiredComponents',
      singlePage: appConfig.singlePage || {},
      supportedMiniProgramVersion: appConfig.supportedMiniProgramVersion || '',
      darkmode: appConfig.darkmode || false,
      themeLocation: appConfig.themeLocation || '',
      libVersion: appConfig.libVersion || '',
      renderer: appConfig.renderer || 'webview',
      rendererOptions: appConfig.rendererOptions || {},
      componentFramework: appConfig.componentFramework || 'glass-easel',
      skeleton: appConfig.skeleton || {},
      ext: appConfig.ext || {},
      entryPagePath: appConfig.entryPagePath || '',
      chatTools: appConfig.chatTools || []
    };

    return JSON.stringify(taroConfig, null, 2);
  }

  private transformProjectConfig(projectConfig: any): string {
    // 转换project.config.json为Taro项目配置
    const taroProjectConfig = {
      miniprogramRoot: projectConfig.miniprogramRoot || './',
      cloudfunctionRoot: projectConfig.cloudfunctionRoot || './cloudfunctions/',
      setting: {
        urlCheck: projectConfig.setting?.urlCheck || true,
        es6: projectConfig.setting?.es6 || true,
        enhance: projectConfig.setting?.enhance || true,
        postcss: projectConfig.setting?.postcss || true,
        preloadBackgroundData: projectConfig.setting?.preloadBackgroundData || false,
        minified: projectConfig.setting?.minified || true,
        newFeature: projectConfig.setting?.newFeature || false,
        coverView: projectConfig.setting?.coverView || true,
        nodeModules: projectConfig.setting?.nodeModules || false,
        autoAudits: projectConfig.setting?.autoAudits || false,
        showShadowRootInWxmlPanel: projectConfig.setting?.showShadowRootInWxmlPanel || true,
        scopeDataCheck: projectConfig.setting?.scopeDataCheck || false,
        uglifyFileName: projectConfig.setting?.uglifyFileName || false,
        checkInvalidKey: projectConfig.setting?.checkInvalidKey || true,
        checkSiteMap: projectConfig.setting?.checkSiteMap || true,
        uploadWithSourceMap: projectConfig.setting?.uploadWithSourceMap || true,
        compileHotReLoad: projectConfig.setting?.compileHotReLoad || false,
        useMultiFrameRuntime: projectConfig.setting?.useMultiFrameRuntime || true,
        useApiHook: projectConfig.setting?.useApiHook || true,
        useApiHostProcess: projectConfig.setting?.useApiHostProcess || true,
        babelSetting: projectConfig.setting?.babelSetting || {
          ignore: [],
          disablePlugins: [],
          outputPath: ''
        },
        enableEngineNative: projectConfig.setting?.enableEngineNative || false,
        useIsolateContext: projectConfig.setting?.useIsolateContext || true,
        userConfirmedBundleSwitch: projectConfig.setting?.userConfirmedBundleSwitch || false,
        packNpmManually: projectConfig.setting?.packNpmManually || false,
        packNpmRelationList: projectConfig.setting?.packNpmRelationList || [],
        minifyWXSS: projectConfig.setting?.minifyWXSS || true,
        disableUseStrict: projectConfig.setting?.disableUseStrict || false,
        minifyWXML: projectConfig.setting?.minifyWXML || true,
        showES6CompileOption: projectConfig.setting?.showES6CompileOption || false,
        useCompilerPlugins: projectConfig.setting?.useCompilerPlugins || false,
        ignoreUploadUnusedFiles: projectConfig.setting?.ignoreUploadUnusedFiles || true
      },
      appid: projectConfig.appid || '',
      projectname: projectConfig.projectname || '',
      libVersion: projectConfig.libVersion || '',
      cloudfunctionTemplateRoot: projectConfig.cloudfunctionTemplateRoot || '',
      condition: projectConfig.condition || {
        search: {
          list: []
        },
        conversation: {
          list: []
        },
        plugin: {
          list: []
        },
        game: {
          list: []
        },
        miniprogram: {
          list: []
        }
      }
    };

    return JSON.stringify(taroProjectConfig, null, 2);
  }

  generateTaroConfig(): string {
    // 生成Taro配置文件
    return `const config = {
  projectName: 'taro-project',
  date: '${new Date().toISOString().split('T')[0]}',
  designWidth: 750,
  deviceRatio: {
    640: 2.34 / 2,
    750: 1,
    828: 1.81 / 2
  },
  sourceRoot: 'src',
  outputRoot: 'dist',
  plugins: [],
  defineConstants: {
  },
  copy: {
    patterns: [
    ],
    options: {
    }
  },
  framework: '${this.config.framework}',
  compiler: 'webpack4',
  mini: {
    postcss: {
      pxtransform: {
        enable: true,
        config: {

        }
      },
      url: {
        enable: true,
        config: {
          limit: 1024
        }
      },
      cssModules: {
        enable: false,
        config: {
          namingPattern: 'module',
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    }
  },
  h5: {
    publicPath: '/',
    staticDirectory: 'static',
    postcss: {
      autoprefixer: {
        enable: true,
        config: {
        }
      },
      cssModules: {
        enable: false,
        config: {
          namingPattern: 'module',
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    }
  }
}

module.exports = function (merge) {
  if (process.env.NODE_ENV === 'development') {
    return merge({}, config, require('./dev'))
  }
  return merge({}, config, require('./prod'))
}
`;
  }
} 